package com.frank.yinyuetai.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.frank.yinyuetai.Adapter.VchartRecycleAdapter;
import com.frank.yinyuetai.Bean.PeriodsBean;
import com.frank.yinyuetai.Bean.VChartBean;
import com.frank.yinyuetai.Bean.VChartPeriod;
import com.frank.yinyuetai.Bean.VideoBean;
import com.frank.yinyuetai.R;
import com.frank.yinyuetai.Util.URLProviderUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/18 0018.
 */
public class VchartBaseFragment extends Fragment {
    @Bind(R.id.srl_vchart)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.vchart_period)
    TextView vchartPeriod;
    @Bind(R.id.period_layout)
    RelativeLayout periodLayout;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    private int position;
    private String areaCode;
    private int dateCode;//默认为最新一期
    private List<VideoBean> mList;
    private VchartRecycleAdapter vchartAdapter;
    protected int mWidth;
    protected int mHeight;
    private List<PeriodsBean> nList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        position = getArguments().getInt("position");
        View view = inflater.inflate(R.layout.vchart_base_fragment, null);
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        nList = new ArrayList<>();
        observerView(360, 640);
        String code=getCurrentMonday();
        dateCode=Integer.parseInt(code);

        vchartAdapter = new VchartRecycleAdapter(mList, this.getActivity(), mWidth, mHeight);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        recyclerView.setAdapter(vchartAdapter);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData();
            }
        });
        switch (position) {
            case 0:
                areaCode = "ML";
                break;
            case 1:
                areaCode = "KR";
                break;
            case 2:
                areaCode = "HT";
                break;
            case 3:
                areaCode = "JP";
                break;
            case 4:
                areaCode = "US";
                break;
        }
        requestData();
        return view;
    }

    public String getCurrentMonday() {

        SimpleDateFormat df=new SimpleDateFormat("y年M月d日 E H时m分s秒", Locale.CHINA);
        Calendar calendar=Calendar.getInstance(Locale.CHINA);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String preMonday = df.format(calendar.getTime());

        //切分时间
        String []withOutYear=preMonday.split("年");
        String []withOutMonth=withOutYear[1].split("月");
        String []withOutDay=withOutMonth[1].split("日");
        if(withOutMonth[0].length()==1){
            withOutMonth[0]="0"+withOutMonth[0];
        }
        if(withOutDay[0].length()==1){
            withOutDay[0]="0"+withOutDay[0];
        }
        String nowMonday=withOutYear[0]+withOutMonth[0]+withOutDay[0];
        return nowMonday;
    }
    private void requestData() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpUtils.getInstance()
                        .get(URLProviderUtil.getVChartListUrl(areaCode, dateCode))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gson = new Gson();
                                VChartBean vBean = gson.fromJson(s, VChartBean.class);
                                List<VideoBean> vList = vBean.getVideos();
                                mList.addAll(vList);
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onAfter(@Nullable String s, @Nullable Exception e) {
                                super.onAfter(s, e);
                                swipeRefreshLayout.setRefreshing(false);
                            }

                        });
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.getInstance()
                        .get(URLProviderUtil.getVChartPeriodUrl(areaCode))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                VChartPeriod vChartPeriod = new Gson().fromJson(s, VChartPeriod.class);
                                List<PeriodsBean> pList = vChartPeriod.getPeriods();
                                nList.addAll(pList);
                                Message message = new Message();
                                message.what = 2;
                                handler.sendMessage(message);
                            }


                        });
            }
        }).start();


    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    vchartAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    vchartPeriod.setText(nList.get(0).getYear() + "年" + nList.get(0).getNo() + "期（" + nList.get(0).getBeginDateText() + "-" + nList.get(0).getEndDateText() + ")");
            }

        }
    };

    public static VchartBaseFragment newInstance(int position) {
        VchartBaseFragment baseFragment = new VchartBaseFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        baseFragment.setArguments(bundle);
        return baseFragment;

    }

    protected void observerView(int imgHeight, int imgWidth) {
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        mWidth = metric.widthPixels;
        mHeight = (mWidth * imgHeight) / imgWidth;
    }
}
